<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item to="/goods">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航End -->

    <el-card>
      <!-- 提示 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 提示End -->

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeTab - 0"
        finish-status="success"
        align-center
        class="mt-15"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 步骤条End -->

      <el-form
        ref="addGoodsForm"
        :model="addGoodsParams"
        :rules="addGoodsRulesForm"
      >
        <!-- 标签面板 -->
        <el-tabs
          tab-position="left"
          class="mt-15"
          v-model="activeTab"
          @tab-click="handleTabSwitch"
          :before-leave="handleTabLeave"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsParams.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                type="number"
                min="0"
                v-model="addGoodsParams.goods_price"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                type="number"
                min="0"
                v-model="addGoodsParams.goods_weight"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                type="number"
                min="0"
                v-model="addGoodsParams.goods_number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <span>选择商品分类: </span>
              <el-cascader
                expand-trigger="hover"
                :props="cascaderProps"
                :options="catesList"
                v-model="addGoodsParams.goods_cat"
                @change="handleSelectCate"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 基本信息End -->

          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1" class="mt-15">
            <el-form-item
              v-for="item in manyDataList"
              :key="item.attr_id"
              :label="item.attr_name"
              class="mt-15"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item2, idx2) in item.attr_vals"
                  :key="idx2"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->

          <!-- 静态属性面板 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyDataList"
              :key="item.attr_id"
              :label="item.attr_name"
              class="mt-15"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(item2, idx2) in item.attr_vals"
                  :key="idx2"
                  :label="item2"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态属性面板End -->

          <!-- 上传图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="requestURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleSuccess"
              :file-list="addGoodsParams.pics"
              list-type="picture"
              :headers="uploadHeaders"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 上传图片End -->

          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              v-model="addGoodsParams.introContent"
              style="height: 600px; overflow-y: auto"
            ></quill-editor>

            <el-button
              type="primary"
              style="margin-top: 15px"
              @click="saveAddGoodsInfo"
              >添加商品</el-button
            >
          </el-tab-pane>
          <!-- 商品内容 -->
        </el-tabs>
        <!-- 标签面板End -->
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="picPreviewDialogVisible"
      width="50%"
    >
      <div><img :src="previewPicUrl" class="previewPic" /></div>
    </el-dialog>
    <!-- 图片预览End -->
  </div>
</template>


<script>
import _ from "lodash";

export default {
  data() {
    return {
      // 商品分类
      catesList: [],
      activeTab: "0",
      // 添加商品表单参数
      addGoodsParams: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        introContent: "",
        attrs: [],
      },
      // 添加商品表单规则
      addGoodsRulesForm: {
        goods_name: [
          { required: true, message: "请输入商品名称!", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格!", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量!", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量!", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类!", trigger: "blur" },
        ],
      },

      cascaderProps: {
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },

      // 图片预览对话框
      picPreviewDialogVisible: false,
      // 当前预览图的路径
      previewPicUrl: "",

      // 动态参数数据
      manyDataList: [],
      // 静态属性数据
      onlyDataList: [],

      // 商品参数选中项
      goodsCheckList: [],

      // 图片上传地址
      requestURL: "http://localhost:8888/api/private/v1/upload",
      uploadFileList: [],
      // 文件上传请求头
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },

  created() {
    // 获取商品分类
    this.getCateList();
  },

  computed: {
    cateId() {
      let len = this.addGoodsParams.goods_cat.length;
      if (len === 3) {
        return this.addGoodsParams.goods_cat[len - 1];
      }
    },
  },

  methods: {
    // 获取商品分类
    async getCateList() {
      let { data: res } = await this.$http("categories");
      if (res.meta.status !== 200)
        return this.$message.error("商品分类获取失败!");
      this.$message.success("商品分类获取成功!");
      console.log(res.data);
      this.catesList = res.data;
    },

    // 改变商品分类选项
    handleSelectCate(cates) {
      this.addGoodsParams.goods_cat = cates.length !== 3 ? [] : cates;
    },

    // 切换标签之前处理的事件
    handleTabLeave(nVal, oVal) {
      if (this.addGoodsParams.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 切换标签
    async handleTabSwitch() {
      console.log(this.cateId);
      // 如果是商品参数,那么就得在切换完成之后发送请求
      if (this.activeTab === "1") {
        let { data: res } = await this.$http(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("动态参数获取失败");
        this.$message.success("动态参数获取成功!");
        this.manyDataList = res.data;
        this.manyDataList.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        console.log(this.manyDataList);
        // 商品属性标签页
      } else if (this.activeTab === "2") {
        let { data: res } = await this.$http(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("静态属性获取失败");
        this.$message.success("静态属性获取成功!");
        this.onlyDataList = res.data;
        this.onlyDataList.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        console.log(this.onlyDataList);
      }
    },

    // 预览已上传的图片
    handlePreview(file) {
      console.log(file);
      if (!file.response.data) return;
      this.picPreviewDialogVisible = true;
      this.previewPicUrl = file.response.data.url;
    },
    // 删除已上传的图片
    handleRemove(file) {
      let tmpPath = file.pic;

      let idx = this.addGoodsParams.pics.findIndex(
        (item) => tmpPath == item.url
      );
      this.addGoodsParams.pics.splice(idx, 1);
    },
    // 监听图片成功上传图片
    handleSuccess(response, file) {
      if (response.response) {
        // response.response.forEach((item) => {
        //   let photoInfo = {
        //     name: item.name,
        //     url: item.response.data.url,
        //   };
        //   this.addGoodsParams.pics.push(photoInfo);
        // });
        // console.log(this.addGoodsParams.pics);

        let photoInfo = {
          name: response.response.name,
          url: response.response.data.url,
        };
        this.addGoodsParams.pics.push(photoInfo);
      }
    },

    // 保存添加商品
    saveAddGoodsInfo() {
      this.$refs.addGoodsForm.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项！");
        console.log(this.addGoodsParams);
        // 处理表单数据
        let cloneForm = _.cloneDeep(this.addGoodsParams);
        cloneForm.goods_cat = cloneForm.goods_cat.join(",");

        // 动态参数
        this.manyDataList.forEach((item) => {
          let info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          cloneForm.attrs.push(info);
        });
        // 静态属性
        this.onlyDataList.forEach((item) => {
          let info = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          cloneForm.attrs.push(info);
        });
          console.log(cloneForm);

          // 发起请求
        let {data:res} = this.$http.post("goods", cloneForm);
        if(res.meta.status !== 201)return this.$message.error("添加商品失败");
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },
  },
};
</script>

<style scoped>
.el-form /deep/ .el-form-item__label {
  float: none;
}
.el-checkbox {
  margin: 5px;
}
.previewPic {
  width: 100%;
  object-fit: cover;
}
</style>